package com.z.common.configure.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.z.common.web.vo.response.Result;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
//public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    @Resource
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        if("json".equals("json")){
            httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "*");
            httpServletResponse.setContentType("application/json;charset=UTF-8");
            httpServletResponse.setStatus(HttpStatus.OK.value());
            Map<String, Object> map = new HashMap<>();
            String msg = "";
            if(e instanceof LockedException){
                msg = "账户已被锁定";
            }else if(e instanceof BadCredentialsException){
                msg = "账户或密码错误";
            }else if(e instanceof DisabledException){
                msg = "账户已被禁用";
            }else {
                msg = "登录失败";
            }
            httpServletResponse.getWriter().write(Result.error(msg).toString());
        }else {
            super.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
        }
    }
}